<?php

require_once APPPATH . 'libraries/PartnerParser/Abstract.php';

/**
 * Kinoperez парсер
 *
 * @author Gennadiy Kozlenko
 */
class PartnerParser_Kinoperez extends PartnerParser_Abstract {

    /**
     * Parse partners link
     */
    public function parse() {
        $content = $this->getContent($this->xmlLink);
        if (!empty($content)) {
            $xml = @simplexml_load_string($content);
            if ($xml) {
                $movies = $xml->xpath('/movie_list/movie');
                if ($movies) {
                    foreach ($movies as $movie) {
                        $externalId = (string) $movie->movie_uri;
                        $entry = new VideoEntry();
                        $title = trim(stripslashes((string) $movie->title));
                        $entry->setTitle($title);
                        $origTitle = trim(stripslashes((string) $movie->title_en));
                        if ($origTitle != $title) {
                            $entry->setOrigTitle($origTitle);
                        }
                        $entry->setYear((int) $movie->year);
                        $videos = $this->searchVideos($entry);
                        foreach ($videos as $idVideo) {
                            $this->registerPartner($idVideo, $this->idPartner, $externalId);
                        }
                    }
                } else {
                    $this->obj->log('Error: Empty movies list');
                }
            } else {
                $this->obj->log('Error: Cannot parse XML');
            }
        } else {
            $this->obj->log('Error: Empty content');
        }
    }

    /**
     * Get contnet
     * @param string $url
     */
    protected function getContent($url) {
        $content = get_content($url, array(), $this->timeout);
        $file = tempnam(BASEPATH . 'cache', 'kinoperez');
        file_put_contents($file, $content);
        if (false !== ($gz = gzopen($file, 'r'))) {
            $content = stream_get_contents($gz);
            gzclose($gz);
        }
        unlink($file);
        return $content;
    }

}